<template>
    <el-dialog :model-value="show" title="分配角色" @close="$emit('hide')">
        <el-select v-model="list" multiple placeholder="Select" style="width: 240px">
            <el-option v-for="item in roles" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <template #footer>
            <el-button @click="$emit('hide', false)">取消</el-button>
            <el-button type="primary" @click="submit">确认</el-button>
        </template>
    </el-dialog>
</template>
<script setup lang='ts'>
import { ElMessage, ElMessageBox } from 'element-plus';
import { ref, watch } from 'vue';
import { getRoleListAPI, getRolesByUserIdAPI, updateUserRolesAPI } from "./api"
const props = defineProps({
    show: {
        type: Boolean,
        default: false
    },
    id: {
        type: Number,
        default: 0
    }
})
const list = ref<number[]>([])
const roles = ref<{ value: number; label: string }[]>([])
const emit = defineEmits(["hide"]);
getRoleListAPI().then(res => {
    if (res.code === 200) {
        roles.value = res.data.map((item) => ({
            label: item.name,
            value: item.id
        }))
    }
})

watch(() => props.id, () => {
    getRolesByUserIdAPI(props.id).then((res) => {
        if (res.code === 200) {
            list.value = res.data.map(item => item.id)
        }
    })
})

const submit = () => {
    ElMessageBox.confirm("确定要修改此用户的角色吗？", "修改用户角色", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: 'warning'
    }).then(() => {
        updateUserRolesAPI(props.id, list.value).then(res => {
            if (res.code === 200) {
                ElMessage.success("修改成功")
                emit('hide')
            }
        })
    }).catch(() => { })
}
</script>
<style lang="less" scoped>

</style>